package com.baizhi.springbootday0201.controller;




import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.net.URLEncoder;
import java.util.UUID;

@Controller
public class FilerDowloadController {








	@RequestMapping("/fileDowload")
	public String fileDowload(MultipartFile file, String name, HttpServletRequest request) throws IOException {
		System.out.println(name+"---");

//		获取项目中文件存档位置的路径
		String realPath = request.getServletContext().getRealPath("upload");
		System.out.println(realPath);
//		 重命名
		String newFileName = UUID.randomUUID().toString().replace("-","")+"_"+file.getOriginalFilename();
		System.out.println(newFileName);

		file.transferTo(new File(realPath+"/"+newFileName));
		return "index";
	}


	@RequestMapping("/upload")
//	文件下载
	public void upload(String name, HttpServletResponse response,HttpServletRequest request) throws IOException {
		System.out.println(name);

//		获取当前项目的文件存放路径
		String path = request.getServletContext().getRealPath("upload");

//		找到对应的文件
		File file = new File(path+"/"+name);


//		设置响应的头信息
		response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(name,"utf-8"));

//		将文件响应出去
		FileCopyUtils.copy(new FileInputStream(file),response.getOutputStream());
	}
}
